#!/bin/env perl

#
# Modules.
#

use lib qw( lib root/SOCK/lib );

use Modern::Perl;

use Getopt::Long;
use iSOCK;
use iSOCK::Model::App;
use SOCK::CSP::Projects;
use SOCK::LOG;
use YAML qw( DumpFile LoadFile );

#
# Options.
#

my $tool = 'isock_sp_vs_db';

my %option;
GetOptions ( \%option, qw{ reuse login=s password=s } ) and ( $option{login} && $option{password} )
  or die "Usage: $tool --login jdoe --password s3kr33t [--reuse]";

#
# Hi.
#

my $log = SOCK::LOG->new ({ file => "$tool.log" });

$log->say_n_right ( "Tool '$tool' started." );

#
# Projects.
#

my $projects;

if ( $option{reuse} ) {
  $log->say_n_right ( "Loading YAML file..." );
  $projects = LoadFile ( 'DR_Summary.yaml' );
  $log->left_n_say ( "Done." );
}
else {
  $log->say_n_right ( "Scrapping SP site..." );
  my $id = SOCK::CSP::Projects->new ({ login => $option{login}, password => $option{password} });
  $id->request;
  DumpFile ( 'DR_Summary.yaml', $id->projects );
  $projects = $id->projects;
  $log->left_n_say ( "Done." );
}

$log->expire ( 'No projects!' ) unless $projects;

#
# DB.
#

if ( my $schema = iSOCK::Model::App->new ) {
  my $product_rs = $schema->resultset ( 'Product' )->search ( {}, { order_by => 'id' } );
  
  $log->say_n_right ( "Updating project ID from die ID..." );
  
  for my $product_r ( $product_rs->search ( { die_id => { '!=' => undef } } ) ) {
    my $die_id = $product_r->die_id;
    
    next unless my ( $project_h ) = grep { $_->{die_id} eq $die_id } @$projects;
    
    if ( !$product_r->pm_id || ( $product_r->pm_id ne $project_h->{id} ) ) {
      $log->say ( "$die_id => " . $product_r->id . " => $project_h->{id}." );

      $product_r->update ({ pm_id => $project_h->{id} });
    }
  }
  
  $log->left_n_say ( "Done." );
  
  $log->say_n_right ( "Updating stage..." );
  
  for my $product_r ( $product_rs->search ( { pm_id => { '!=' => undef } } ) ) {
    my $pm_id = $product_r->pm_id;
    
    next unless my ( $project_h ) = grep { $_->{id} eq $pm_id } @$projects;
    
    if ( !$product_r->stage_id || ( $product_r->stage_id ne $project_h->{stage} ) ) {
      $log->say ( $product_r->id . ": " . ( $product_r->stage_id || 'N/A' ) . " => $project_h->{stage}." );
      
      $product_r->update ({ stage_id => $project_h->{stage} });
    }
  }
  
  $log->left_n_say ( "Done." );
}

#
# Bye.
#

$log->left_n_say ( "Done." );
